package cn.edu.zut.mock;

import cn.edu.zut.bean.Price_rule;
import com.github.javafaker.Faker;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class PriceRuleDataGenerator {

    private static final String DB_URL = "jdbc:mysql://hadoop102:3306/driver?allowPublicKeyRetrieval=true&useSSL=false&requireSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "000000";
    private static final int BATCH_SIZE = 100;
    // 缓存 city_ids 避免重复查询
    private static List<String> cityIdCache = null;
    private static final Random random = new Random();

    /**
     * 从 city 表中随机获取一个 city_id
     */
    public static String randomCityId() {
        if (cityIdCache == null || cityIdCache.isEmpty()) {
            cityIdCache = getAllCityIds();
        }

        if (cityIdCache == null || cityIdCache.isEmpty()) {
            throw new IllegalStateException("city 表中没有可用的 city_id");
        }

        return cityIdCache.get(random.nextInt(cityIdCache.size()));
    }

    /**
     * 查询所有 city_id
     */
    public static List<String> getAllCityIds() {
        List<String> cityIds = new ArrayList<>();
        String query = "SELECT city_id FROM city"; // 替换为你的城市表名

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {

            while (rs.next()) {
                cityIds.add(rs.getString("city_id"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if (cityIds.isEmpty()) {
            throw new RuntimeException("city 表中没有可用的 city_id");
        }

        return cityIds;
    }

    public static void main(String[] args) {
        // 每次运行追加10条数据
        int count = 10;
        generateData(count);
    }

    public static void generateData(int count) {
        Faker faker = new Faker(Locale.CHINA);
        List<Price_rule> rules = new ArrayList<>();

        // 获取数据库中已有的最大id
        long startId = getMaxId() + 1;

        for (long i = startId; i < startId + count; i++) {
            Price_rule rule = Price_rule.builder()
                    .id(String.valueOf(i)) // 假设id是手动设置的
                    .city_id(randomCityId())
                    .car_type(generateRandomCarType(faker))
                    .base_price(String.valueOf(faker.number().randomDouble(2, 10, 20)))
                    .price_per_km(generateRandompk(faker))
                    .price_per_min(generateRandommk(faker))
                    .build();
            rules.add(rule);
        }

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            conn.setAutoCommit(false);
            String sql = "INSERT INTO price_rule (id, city_id, car_type, base_price, price_per_km, price_per_min) VALUES (?, ?, ?, ?, ?, ?)";

            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                for (int i = 0; i < rules.size(); i++) {
                    Price_rule rule = rules.get(i);
                    pstmt.setString(1, rule.getId()); // 假设id是手动设置的
                    pstmt.setString(2, rule.getCity_id());
                    pstmt.setString(3, rule.getCar_type());
                    pstmt.setString(4, rule.getBase_price());
                    pstmt.setDouble(5, rule.getPrice_per_km());
                    pstmt.setDouble(6, rule.getPrice_per_min());
                    pstmt.addBatch();

                    if ((i + 1) % BATCH_SIZE == 0) {
                        pstmt.executeBatch();
                    }
                }
                pstmt.executeBatch();
                conn.commit();
                System.out.println("成功插入" + count + "条价格规则");
            } catch (SQLException e) {
                conn.rollback();
                e.printStackTrace();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询数据库中已有的最大id
     */
    private static long getMaxId() {
        String sql = "SELECT MAX(CAST(id AS SIGNED)) FROM price_rule"; // 替换为你的表名
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            if (rs.next()) {
                return rs.getLong(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0; // 如果表为空，返回0
    }

    private static String generateRandomCarType(Faker faker) {
        String[] carTypes = {"SUV", "MPV", "轿车", "面包车", "商务车", "皮卡"};
        return carTypes[faker.random().nextInt(carTypes.length)];
    }

    private static double generateRandompk(Faker faker) {
        return Math.round(faker.number().randomDouble(2, 1, 3));
    }

    private static double generateRandommk(Faker faker) {
        return Math.round(faker.number().randomDouble(2, 1, 2));
    }
}